<!--
*@Author: QWP
*@Description: 人员编辑
*@Date: 2023-06-29 17:03:08
-->
<template>
  <u-dialog
    v-bind="$attrs"
    @submit="submit"
    @close="dialgoClose">
    <u-loading-box :spinning="loading">
      <u-busi-card
        title="人员信息"
        icon="jbxx">
        <u-form
          :elements="elements"
          :model="form"
          ref="formRef">
        </u-form>
      </u-busi-card>

      <!-- 角色权限 -->
      <a-checkbox-group
        v-model:value="form.userroles"
        class="f-w-100"
        style="display: flex; flex-direction: column">
        <template v-for="item in roleGroupDatas">
          <u-busi-card
            :title="item.label"
            icon="jbxx"
            :key="item.label"
            v-if="item.data.length != 0"
            class="f-w-100">
            <a-row class="f-w-100">
              <a-col
                :span="3"
                v-for="role in item.data">
                <a-checkbox :value="role.keyid">{{ role.rolename }}</a-checkbox>
              </a-col>
            </a-row>
          </u-busi-card>
        </template>
      </a-checkbox-group>
    </u-loading-box>
  </u-dialog>
</template>
<script lang="ts" setup>
import { nullC } from "@/util/common";
import { fileCols } from "@/common/model/fileCols.js";
import * as userService from "@/service/system/user/index";
import * as deptService from "@/service/system/dept/index";
import * as roleService from "@/service/system/role/index";
import * as userRoleService from "@/service/system/user_role/index";
import { computed, reactive, ref, useAttrs } from "vue";
import { storeToRefs } from "pinia";
import { useBaseStore, useLoginStore } from "@/store";
import { alertC, confirmC, isValue, messageC } from "@/util/common";
import { watch } from "vue";

const { userInfo } = storeToRefs(useLoginStore());
const { DEPT_TYPE, POST, OVERTIME_EMP_TYPE, STATUS, ROLE_TYPE, POS, deptData } = storeToRefs(useBaseStore());
const attrs = useAttrs();
const emit = defineEmits(["success"]);

const loading = ref(false);
let form = reactive<any>({
  fkdeptid: "",
  fkunitsid: "",
  loginname: "",
  usercode: "",
  username: "",
  nickname: "",
  gender: "",
  entrydate: "",
  travelstandard: "",
  printposition: "",
  emptype: "",
  userstatus: "",
  businesscard: "",
  businessbank: "",
  paycard: "",
  paybank: "",
  idcard: "",
  tel: "",
  telshort: "",
  remark: "",
  keyid: "",
  userroles: [],
});
const formItemProps = {
  labelWidth: "110px",
  colon: false,
};

let elements = reactive<any>([
  // {element: 'select', label: '所在单位',  col: { span: 8 }, key: 'fkUnitsId', data: [], required: true,},
  {
    element: "select",
    label: "所在部门",
    col: { span: 8 },
    key: "fkdeptid",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: deptData.value,
      required: true,
    },
  },
  // {
  //   element: "input",
  //   label: "登录名",
  //   col: { span: 8 },
  //   key: "loginname",
  //   formItemProps: { ...formItemProps, required: true },
  //   componentProps: {
  //     required: true,
  //     maxLength: 50,
  //   },
  // },
  {
    element: "input",
    label: "人员代码",
    col: { span: 8 },
    key: "usercode",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      required: true,
      maxLength: 50,
      rules: [{ pattern: /\d+$/g, message: "角色代码只能输入数字!", trigger: "blur" }],
    },
  },
  {
    element: "input",
    label: "人员姓名",
    col: { span: 8 },
    key: "username",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      required: true,
      maxLength: 50,
    },
  },
  {
    element: "input",
    label: "昵称/拼音",
    col: { span: 8 },
    key: "nickname",
    maxlength: "50",
    "show-word-limit": true,
    formItemProps: { ...formItemProps },
  },
  {
    element: "select",
    label: "性别",
    col: { span: 8 },
    key: "gender",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: computed(() => [
        { keyid: "1", name: "男" },
        { keyid: "2", name: "女" },
      ]),
      fieldNames: { label: "name", value: "keyid" },
      required: true,
    },
  },
  {
    element: "datepicker",
    label: "入职日期",
    col: { span: 8 },
    key: "entrydate",
    formItemProps: { ...formItemProps, required: false },
  },
  // { element: 'select', label: '差旅标准', col: { span: 8 }, key: 'travelstandard',
  //   formItemProps: { ...formItemProps, required: true },
  //   componentProps: {
  //     options: POST.value, fieldNames: { label: "name", value: "id" }, required: false,
  //   }
  // },
  // {
  //   element: 'select', label: '审核打印位置', col: { span: 8 }, key: 'printposition',
  //   componentProps: {
  //     options: POS.value, fieldNames: { label: "name", value: "id" }, required: true,
  //   }
  //   // data: POS.value
  // },
  // {
  //   element: 'select', label: '人员类型', col: { span: 8 }, key: 'emptype',
  //   formItemProps: { ...formItemProps, required: true },
  //   componentProps: {
  //     options: OVERTIME_EMP_TYPE.value, fieldNames: { label: "name", value: "id" }, required: true
  //   }
  // },
  {
    element: "select",
    label: "人员状态",
    col: { span: 8 },
    key: "userstatus",
    required: true,
    data: [],
    baseKey: "STATUS",
    props: { label: "name" },
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: STATUS.value,
      fieldNames: { label: "name", value: "id" },
      required: true,
    },
  },
  // {
  //   element: 'input', label: '公务卡号', col: { span: 8 }, key: 'businesscard',
  //   maxlength: "50", 'show-word-limit': true
  // },
  // {
  //   element: 'input', label: '公务卡银行', col: { span: 8 }, key: 'businessbank',
  //   maxlength: "50", 'show-word-limit': true
  // },
  // {
  //   element: 'input', label: '工资卡号', col: { span: 8 }, key: 'paycard',
  //   maxlength: "50", 'show-word-limit': true
  // },
  // {
  //   element: 'input', label: '工资卡银行', col: { span: 8 }, key: 'paybank',
  //   maxlength: "50", 'show-word-limit': true
  // },
  {
    element: "input",
    label: "证件号码",
    col: { span: 8 },
    key: "idcard",
    formItemProps: { ...formItemProps, required: false },
    maxlength: "50",
    "show-word-limit": true,
  },
  {
    element: "input",
    label: "电话号码",
    col: { span: 8 },
    key: "tel",
    formItemProps: { ...formItemProps, required: true },
    maxlength: "50",
    "show-word-limit": true,
  },
  {
    element: "input",
    label: "短号",
    col: { span: 8 },
    key: "telshort",
    formItemProps: { ...formItemProps, required: false },
    maxlength: "50",
    "show-word-limit": true,
  },
  {
    element: "textarea",
    label: "备注",
    type: "textarea",
    col: { span: 24 },
    key: "remark",
    formItemProps: { ...formItemProps, required: false },
    maxlength: "200",
    "show-word-limit": true,
  },
]);

const roleGroupDatas = ref<any[]>([]);

// 获取分组角色信息
const getRolesData = async () => {
  try {
    const res = await roleService.roleGroup()
    if (res.code == 0) {
      roleGroupDatas.value = [];
      for (let key in res.data) {
        let roleType = ROLE_TYPE.value.find((i) => i.id == key) || {};
        roleGroupDatas.value.push({
          label: roleType["name"] || "",
          data: res.data[key] || [],
        });
      }
    }
  } catch (error) {}
};

const formRef = ref();
// 保存用户提交事件
const submit = async () => {
  try {
    await formRef.value.form.validate()
  } catch (error) {
    messageC("请先将表单必填项填写完毕！");
    return
  }

  loading.value = true;
  try {
    const verifyName = await userService.check({ name: form.loginname });
    // 验证登录名是否可用
    if (verifyName.code != 0) {
      messageC(verifyName.data.msg);
      loading.value = false;
      return;
    }
  } catch (error) {}

  try {
    const url = attrs.id == "" ? "add" : "update";
    // 修改
    if (attrs.id) {
      form.keyid = attrs.id;
    }

    // 新增
    else {
      form.fkunitsid = attrs.fkunitsid;
    }
 
    if (form.fkunitsid instanceof Array) {
      form.fkunitsid = form.fkunitsid[form.fkunitsid.length - 1];
    }

    const res = await userService[url](form)
    if (res.code == 0) {
      alertC(res.msg, "success");
      dialgoClose()
      emit("success");
    } else {
      alertC(res.msg, "warning");
    }
  } catch (error) {}
  loading.value = false;
};

// 修改回显数据
const echoInfo = async () => {
  loading.value = true;
  try {
    const res = await userService.query(attrs.id)
    if (res.code == 0) {
      for (let key in form) {
        if (key != "userroles") {
          form[key] = res.data[key];
        }
      }
      form.gender += "";
      form.travelstandard += "";
      form.emptype += "";
      form.userstatus += "";
    }
  } catch (error) {}
  loading.value = false;
};

// 修改角色信息回显
const echoRoleInfo = async () => {
  loading.value = true;
  try {
    const res = await userRoleService.rolesByUserId(attrs.id)
    if(res.code == 0) {
      form.userroles = res.data;
    }
  } catch (error) {}
  loading.value = false;
};

// 弹窗关闭
const dialgoClose = () => {
  loading.value = false;
  form["userroles"] = [];
  formRef.value.form.resetFields();
};

watch(
  () => attrs.open,
  (nval) => {
    if (nval == true) {
      getRolesData();
      form.keyid = attrs.id;
      if (attrs.id) {
        echoInfo();
        echoRoleInfo();
      }
    }
  }
);
</script>
<style lang="scss"></style>
